﻿using System;
using System.Collections;
using System.Data;
//using System.Data.Odbc;//.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using Com.Becom.CommonLibrary.Common;
using System.Reflection;
using MySql.Data.MySqlClient;
namespace Com.Becom.CommonLibrary.Db.AdoNet
{
    /// <summary>
    /// 数据库的通用访问代码
    /// 此类为抽象类，不允许实例化，在应用时直接调用即可
    /// </summary>
    public abstract class SqlHelper
    {
        //获取数据库连接字符串，其属于静态变量且只读，项目中所有文档可以直接使用，但不能修改
        // public static readonly string ConnectionStringLocalTransaction = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;
        // 哈希表用来存储缓存的参数信息，哈希表可以存储任意类型的参数。
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        private static string connectionStr;
        //public static IDbCommand command;
        //private static IDbConnection connection;
        private static AbstractDb abstractDb;

        static SqlHelper()
        {
            try
            {
                
                abstractDb = DbManager.CreateAbstractDb();
                //connection = abstractDb.GetDbConnection();
                //connectionStr = abstractDb.GetDbConnectionString();
                //command = abstractDb.GetDbCommand(connectionStr);
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), false, MethodInfo.GetCurrentMethod());
            }
        }
       
        public static void SetConnectionString(string connectionString)
        {
            connectionStr = connectionString;
        }
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public static bool ExecuteSqlTran(List<String> SQLStringList)
        {
            IDbConnection connection = GetCon();
            bool ret = false;
            //if (connection.State != ConnectionState.Open)
            //{
            //    connection.Open();
            //}
            IDbCommand command = abstractDb.GetDbCommand(connectionStr);
            command.Connection = connection;
            IDbTransaction tr = connection.BeginTransaction();
            command.Transaction = tr;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        command.CommandText = strsql;
                        command.CommandType = CommandType.Text;
                        count += command.ExecuteNonQuery();
                    }
                }
                tr.Commit();
                if (count > 0)
                {
                    ret = true;
                }
                //return ret;
            }
            catch
            {
                tr.Rollback();
                ret = false;
                //return false;
            }
            finally
            {
                connection.Close();
            }
            return ret;
        }
        /// <summary>
        /// 获取连接
        /// </summary>
        /// <returns></returns>
        public static IDbConnection GetCon()
        {
            IDbConnection connection = abstractDb.GetDbConnection();//.GetDbConnection(connectionStr);
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            return connection;
        }

        /// <summary>
        /// 获取参数数组
        /// </summary>
        /// <param name="cmdParamName">参数名数组</param>
        /// <param name="cmdParamValue">对应参数值数组</param>
        /// <returns></returns>
        public static DbParameter[] GetDbParameter(object[] cmdParamName, object[] cmdParamValue)
        {
            try
            {
                return abstractDb.GetDbParameter(cmdParamName, cmdParamValue);
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
        }

        /// <summary>
        /// 向现有参数追加一个带有输出类型的参数
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="paramName"></param>
        /// <param name="paramValue"></param>
        /// <param name="direction"></param>
        /// <returns></returns>
        public static DbParameter[] AppendDbParameter(DbParameter[] parameters, object paramName, object paramValue, ParameterDirection direction)
        {
            try
            {
                DbParameter[] paras;
                if (parameters == null || parameters.Length == 0)
                    paras = new DbParameter[1];
                else
                {
                    paras = new DbParameter[parameters.Length + 1];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        paras[i] = parameters[i];
                    }
                }
                paras[paras.Length - 1] = abstractDb.GetDbParameter(paramName, paramValue, direction);
                return paras;
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
        }
        /// <summary>
        /// 获取参数数组
        /// </summary>
        /// <param name="cmdParamName">参数名数组</param>
        /// <param name="cmdParamValue">对应参数值数组</param>
        /// <returns></returns>
        public static DbParameter[] GetDbParameter(object cmdParamName, object cmdParamValue)
        {
            try
            {
                return abstractDb.GetDbParameter(cmdParamName, cmdParamValue);
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
        }
        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令，通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <remarks>
        /// 使用示例：
        ///  int result = ExecuteNonQuery(CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] commandParameters)
        {
            IDbConnection con = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, con, null, cmdType, cmdText, commandParameters);
                int val = command.ExecuteNonQuery();
                return val;
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());

                throw ex;
            }
            finally
            {
                con.Close();
            }
        }

        /// <summary>
        /// 执行一条不返回结果的SqlCommand，通过一个已经存在的数据库事物处理 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例： 
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">一个存在的 sql 事物处理</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecuteNonQuery(MySqlTransaction trans, CommandType cmdType, string cmdText, params DbParameter[] commandParameters)
        {
            
            IDbConnection con = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, trans.Connection, trans, cmdType, cmdText, commandParameters);
                int val = command.ExecuteNonQuery();
                return val;
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }

        /// <summary>
        /// 执行带返回值的存储过程
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <param name="returnValue"></param>
        /// <param name="returnMessage"></param>
        /// <param name="commandParameters"></param>
        public static void ExecuteStoredProcedure(string storedProcedureName, out int returnValue, out string returnMessage, params DbParameter[] commandParameters)
        {
            IDbConnection con = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                commandParameters = AppendDbParameter(commandParameters, "@rst_status", null, ParameterDirection.Output);
                commandParameters = AppendDbParameter(commandParameters, "@rst_message", null, ParameterDirection.Output);
                commandParameters[commandParameters.Length - 2].DbType = DbType.Int32;//rst_status
                commandParameters[commandParameters.Length - 1].Size = 255;//rst_message
                //ExecuteNonQuery(CommandType.StoredProcedure, storedProcedureName, commandParameters);
                PrepareCommand(command, con, null, CommandType.StoredProcedure, storedProcedureName, commandParameters);
                int val = command.ExecuteNonQuery();
                returnValue = int.Parse(((MySqlParameter)command.Parameters["@rst_status"]).Value.ToString());
                returnMessage = ((MySqlParameter)command.Parameters["@rst_message"]).Value.ToString();
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="aStarIndex"></param>
        /// <param name="nPageSize"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet GetPageData(string strSql, int aStarIndex, int nPageSize, params DbParameter[] commandParameters)
        {
            DataSet dataSet = new DataSet();
            IDbConnection con = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, con, null, CommandType.Text, strSql, commandParameters);
                MySqlDataAdapter adapter = new MySqlDataAdapter();
                adapter.SelectCommand = (MySqlCommand)command;
                adapter.Fill(dataSet, aStarIndex, nPageSize, "data");
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                con.Close();
            }
            return dataSet;
        }

        public static ArrayList ExecStoreProcReader(string strStoreName, string[] strParams, object[] strValues)
        {
            MySqlDataReader reader = null;
            ArrayList list = null;
            IDbConnection connection = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, connection, null, CommandType.StoredProcedure, strStoreName, GetDbParameter(strParams, strValues));
                reader = ((MySqlCommand)command).ExecuteReader();
                if (reader.Read())
                {
                    list = new ArrayList(reader.FieldCount);
                    for (int num = 0; num < reader.FieldCount; num++)
                    {
                        KeyValuePair<string, object> pair = new KeyValuePair<string, object>(reader.GetName(num).ToLower(), reader.GetValue(num));
                        list.Add(pair);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                reader.Close();
                connection.Close();
            }
            return list;
        }

        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令，通过专用的连接字符串。
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  SqlDataReader r = ExecuteReader(CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</parasm>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        public static IDataReader ExecuteReader(CommandType cmdType, string cmdText, params DbParameter[] commandParameters)
        {
            // 在这里使用try/catch处理是因为如果方法出现异常，则SqlDataReader就不存在，
            //CommandBehavior.CloseConnection的语句就不会执行，触发的异常由catch捕获。
            //关闭数据库连接，并通过throw再次引发捕捉到的异常。
            IDbConnection connection = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, connection, null, cmdType, cmdText, commandParameters);
                IDataReader rdr = command.ExecuteReader(CommandBehavior.CloseConnection);
                return rdr;
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令，通过专用的连接字符串。 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  Object obj = ExecuteScalar(CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        public static object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] commandParameters)
        {
            IDbConnection connection = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, connection, null, cmdType, cmdText, commandParameters);
                object val = command.ExecuteScalar();
                return val;
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodInfo.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// 获取数据集。
        /// </summary>
        /// <param name="SQLCommand">数据查询SQL语句命令行。</param>
        /// <returns>查询结果数据集</returns>
        public static DataSet GetDataSet(CommandType cmdType, string cmdText, params DbParameter[] commandParameters)
        {
            IDbConnection connection = GetCon();
            try
            {
                IDbCommand command = abstractDb.GetDbCommand(connectionStr);
                PrepareCommand(command, connection, null, cmdType, cmdText, commandParameters);
                IDbDataAdapter sqlDataAdapter = (IDbDataAdapter)abstractDb.GetDbDataAdapter();
                sqlDataAdapter.SelectCommand = command;
                DataSet dataSet = new DataSet();
                sqlDataAdapter.Fill(dataSet);
                return dataSet;
            }
            catch (Exception ex)
            {
                AppLog.WriteLog(ex.ToString(), true, MethodBase.GetCurrentMethod());
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }
        /// <summary>
        /// 为执行命令准备参数
        /// </summary>
        /// <param name="cmd">SqlCommand 命令</param>
        /// <param name="conn">已经存在的数据库连接</param>
        /// <param name="trans">数据库事物处理</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="cmdText">Command text，T-SQL语句 例如 Select * from Products</param>
        /// <param name="cmdParms">返回带参数的命令</param>
        private static void PrepareCommand(IDbCommand cmd, IDbConnection conn, IDbTransaction trans, CommandType cmdType, string cmdText, params DbParameter[] cmdParms)
        {
            //判断数据库连接状态
            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            //判断是否需要事物处理
            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;
            cmd.Parameters.Clear();
            if (cmdParms != null)
            {
                foreach (DbParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        #region 原始方法

        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令，通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <remarks>
        /// 使用示例：
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {

            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();

                //清空SqlCommand中的参数列表
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        ///执行一条不返回结果的SqlCommand，通过一个已经存在的数据库连接 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个现有的数据库连接</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        static int ExecuteNonQuery(MySqlConnection connection, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {

            MySqlCommand cmd = new MySqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行一条不返回结果的SqlCommand，通过一个已经存在的数据库事物处理 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例： 
        ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">一个存在的 sql 事物处理</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        //static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        //{
        //    SqlCommand cmd = new SqlCommand();
        //    PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
        //    int val = cmd.ExecuteNonQuery();
        //    cmd.Parameters.Clear();
        //    return val;
        //}

        /// <summary>
        /// 执行一条返回结果集的SqlCommand命令，通过专用的连接字符串。
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个包含结果的SqlDataReader</returns>
        static MySqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();
            MySqlConnection conn = new MySqlConnection(connectionString);

            // 在这里使用try/catch处理是因为如果方法出现异常，则SqlDataReader就不存在，
            //CommandBehavior.CloseConnection的语句就不会执行，触发的异常由catch捕获。
            //关闭数据库连接，并通过throw再次引发捕捉到的异常。
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令，通过专用的连接字符串。 
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例：  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 执行一条返回第一条记录第一列的SqlCommand命令，通过已经存在的数据库连接。
        /// 使用参数数组提供参数
        /// </summary>
        /// <remarks>
        /// 使用示例： 
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">一个已经存在的数据库连接</param>
        /// <param name="commandType">SqlCommand命令类型 (存储过程， T-SQL语句， 等等。)</param>
        /// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个object类型的数据，可以通过 Convert.To{Type}方法转换类型</returns>
        static object ExecuteScalar(MySqlConnection connection, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {

            MySqlCommand cmd = new MySqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        #endregion

        /// <summary>
        /// 缓存参数数组
        /// </summary>
        /// <param name="cacheKey">参数缓存的键值</param>
        /// <param name="cmdParms">被缓存的参数列表</param>
        static void CacheParameters(string cacheKey, params MySqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// 获取被缓存的参数
        /// </summary>
        /// <param name="cacheKey">用于查找参数的KEY值</param>
        /// <returns>返回缓存的参数数组</returns>
        static MySqlParameter[] GetCachedParameters(string cacheKey)
        {
            MySqlParameter[] cachedParms = (MySqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            //新建一个参数的克隆列表
            MySqlParameter[] clonedParms = new MySqlParameter[cachedParms.Length];

            //通过循环为克隆参数列表赋值
            for (int i = 0, j = cachedParms.Length; i < j; i++)
                //使用clone方法复制参数列表中的参数
                clonedParms[i] = (MySqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

    }
}